package com.sunchangming.stmdb;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

public class DebugModule implements Module {
	private static final int PORT = 7755;
	private NioSocketAcceptor acceptor;

	private static class ServerHandler extends IoHandlerAdapter {
		@Override
		public void messageReceived(IoSession session, Object message) throws Exception {
			final String str = message.toString();
			if (str.trim().equalsIgnoreCase("quit")) {
				session.close(false);
				return;
			}
			final String response = "\r\n" + (char) 0x1B + "[31m" + str.trim() + (char) 0x1B + "[m" + "\r\n";
			final IoBuffer res = IoBuffer.wrap(response.getBytes("GBK"));
			session.write(res);
		}

	}

	@Override
	public void init() throws Exception {
		acceptor = new NioSocketAcceptor();
		acceptor.getFilterChain().addLast("codec",
				new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("GBK"))));
		acceptor.setHandler(new ServerHandler());
		acceptor.bind(new InetSocketAddress(PORT));
	}

	@Override
	public void fini() {
		acceptor.setCloseOnDeactivation(false);
		acceptor.unbind();
		for (final IoSession ioSession : acceptor.getManagedSessions().values()) {
			if (ioSession.isConnected())
				ioSession.close(true);
		}
		acceptor.dispose();
		acceptor = null;
	}

}
